package com.aliang.chat.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import javax.imageio.ImageIO;

import cn.hutool.core.io.FileUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

/**
 * 视频工具
 * @author 
 *
 */
public class VideoUtil {
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    /**
     * 获取指定视频的帧并保存为图片至指定目录
     * @param file  源视频文件
     * @param fileName  视频路径
     * @throws Exception
     */
    public static String fetchPic(InputStream file, String fileName) throws Exception{
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file); 
        ff.start();
        int lenght = ff.getLengthInFrames();
        fileName = fileName.replace("mp4","jpg");
        File targetFile = new File(filePath  + fileName);
        int i = 0;
        Frame frame = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            frame = ff.grabFrame();
            if ((i > 5) && (frame.image != null)) {
                break;
            }
            i++;
        }

        Java2DFrameConverter converter =new Java2DFrameConverter();
        BufferedImage srcBi =converter.getBufferedImage(frame);
        int owidth = srcBi.getWidth();
        int oheight = srcBi.getHeight();
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        //画图
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(srcBi.getScaledInstance(width, height, Image.SCALE_SMOOTH),0, 0, null);
        try {
            ImageIO.write(bi, "jpg", targetFile);
        }catch (Exception e) {
            e.printStackTrace();
        }      
        ff.stop();
        return fileName;
    }
}